/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package axil.definition;

import axil.api.AxilType;
import axil.engine.Repository;
import axil.framework.validation.Validated;
import axil.framework.validation.ValidationContext;
import axil.framework.xml.InputXML;
import axil.stdlib.collection.type.Range;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static axil.framework.Functions.msg;
import static axil.framework.Functions.split;


/**
 * The XML-based definition of a set of supported units for a unitized type.
 */
public class Units implements Validated {
	private String defval;
	private String bases;
	private List<UnitDefinition> units;

	private transient TypeDefinition type;
	private transient UnitDefinition baseline;
	private transient Map<String,AxilType> types;


	public Units(InputXML xml) {
		defval = xml.text("baseline");
		bases = xml.text("base-type");
		units = xml.objects(UnitDefinition.class, "units", "unit", Range.some);
	}


	final void link(TypeDefinition type) {
		this.type = type;
	}


	public List<UnitDefinition> units()	{
		return units;
	}


	public UnitDefinition baseline() {
		assert baseline != null;
		return baseline;
	}


	/**
	 * Tell if the type for representing these units can be created from this
	 * base type. For example, "distance" would be the unitized type, and
	 * "integer" would be the base type.
	 */
	public boolean supports(AxilType base) {
		return types.containsKey(base.identity());
	}


	/**
	 * Get the actual type (not the base type) used for representing objects
	 * of these units. The type returned is never null. Note that the type
	 * returned may not actually be supported for a particular compilation
	 * context.
	 */
	public AxilType type() {
		assert type != null;
		return type.type();
	}


	/**
	 * Validate this object in the given context. Any problems detected with the
	 * correctness or completeness of this object are placed into the context.
	 * This method descends into its owned members, validating them as well.
	 */
	public void validate(ValidationContext context) {
		context.required("base", defval);
		context.validate("units", units);
		for (UnitDefinition unit : units) {
			if (unit.name().equals(defval)) {
				baseline = unit;
			}
			unit.link(this);
			Repository.instance().unit(unit);
		}
		if (baseline == null) {
			context.error("baseline", msg(Definition.ns, "undefined-baseline-unit"));
		}

		types = new HashMap<String, AxilType>();
		for (String ident : split(bases)) {
			AxilType t = Repository.instance().find(ident);
			if (t == null) {
				context.error("base-type", msg(Definition.ns, "unknown-base-type"));
			} else {
				types.put(t.identity(), t);
			}
		}
	}


	/**
	 * Compress this object, reducing its memory footprint as much as possible.
	 * A compressed object is still fully functional for script evaluation but
	 * may no longer possess complete metadata.
	 */
	public void compress() {
		for (UnitDefinition unit : units) {
			unit.compress();
		}
	}
}
